package com.samoiloff.util.data {
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	/**
	 * @author Samoiloff  http://samoiloff.com/
	 */
	public class ArrItemCloneDispatcher extends ArrItemDispatcher {
		
		private var _cloneEvents : Array;
		
		public function ArrItemCloneDispatcher() {
			super();
		}
		
		
		override public function destroy() : void {
			for (var i : int = length - 1; i >= 0; i--) {
				removeItem(_arr[i]);
			}
			super.destroy();
		}
		
		override public function addItem(item : Object) : void {
			if (_cloneEvents) {
				var d : IEventDispatcher = item as IEventDispatcher;
				for (var i : int = 0; i < _cloneEvents.length; i++) {
					d.addEventListener(_cloneEvents[i], dispatchEvent);
				}
			}
			super.addItem(item);
		}
		
		override public function removeItem(item : Object) : Object {
			if (_cloneEvents) {
				var d : IEventDispatcher = item as IEventDispatcher;
				for (var i : int = 0; i < _cloneEvents.length; i++) {
					d.removeEventListener(_cloneEvents[i], dispatchEvent);
				}
			}
			return super.removeItem(item);
		}

		public function get cloneEvents() : Array {
			return _cloneEvents;
		}

		public function set cloneEvents(cloneEvents : Array) : void {
			var i:int;
			var j:int;
			var d:EventDispatcher;

			if (_cloneEvents && _arr) {
				for (i = 0; i < length; i++) {
					d = _arr[i] as EventDispatcher;
					for (j = 0; j < _cloneEvents.length; j++) {
						d.removeEventListener(_cloneEvents[j], dispatchEvent);
					}
				}
			}
			
			_cloneEvents = cloneEvents;
			if (_cloneEvents && _arr) {
				for (i = 0; i < length; i++) {
					d = _arr[i] as EventDispatcher;
					for (j = 0; j < _cloneEvents.length; j++) {
						d.addEventListener(_cloneEvents[j], dispatchEvent);
					}
				}
			}
		}
		
	}
}
